package tool

import (
	"archive/zip"
	"fmt"
	"io"
	common "jihe.common"
	"jihe.common/oss"
	"os"
	"time"
)

func UploadImgAndGetCpZip(urls []string) (zipUrl string, err error) {
	files := make([]*os.File, 0)
	tempFiles := make([]string, 0)
	for _, url := range urls {
		_, pngB, errs := GetRequest().Get(url).EndBytes()
		if len(errs) != 0 {
			err = errs[0]
			return
		}
		tempFile := fmt.Sprintf("%s%d.png", os.TempDir(), GetSnowflakeId())
		tempFileF, err := os.Create(tempFile)
		if err != nil {
			return "", err
		}
		tempFileF.Write(pngB)
		df, err := os.Open(tempFileF.Name())
		files = append(files, df)
		tempFileF.Close()
		tempFiles = append(tempFiles, tempFile)
	}
	zipTempFile := fmt.Sprintf("%s%d.zip", os.TempDir(), GetSnowflakeId())
	err = Compresses(files, zipTempFile)
	if err != nil {
		return
	}
	//压缩完毕，删除掉临时文件
	go func() {
		for _, v := range tempFiles {
			os.Remove(v)
		}
	}()
	//将压缩文件上传oss
	bucket, err := oss.GetClient().Bucket("jihe-file")
	if err != nil {
		return
	}
	path := fmt.Sprintf("%s/%d.zip", time.Now().Format("2006-01-02"), GetSnowflakeId())
	err = bucket.PutObjectFromFile(path, zipTempFile)
	if err != nil {
		return
	}
	zipUrl = fmt.Sprintf("%s/%s", common.Configer.Oss.Domain, path)
	//删掉临时zip
	os.Remove(zipTempFile)
	return
}

func Compresses(files []*os.File, dest string) error {
	d, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer d.Close()
	w := zip.NewWriter(d)
	defer w.Close()
	for _, file := range files {
		err := compress(file, w)
		if err != nil {
			return err
		}
	}
	return nil
}

func compress(file *os.File, zw *zip.Writer) error {
	info, err := file.Stat()
	if err != nil {
		return err
	}
	header, err := zip.FileInfoHeader(info)
	if err != nil {
		return err
	}
	writer, err := zw.CreateHeader(header)
	if err != nil {
		return err
	}
	_, err = io.Copy(writer, file)
	if err != nil {
		return err
	}
	defer file.Close()
	return nil
}
